# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testcase.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019-11-19
# -------------------------------------------------------------------------------

import django_filters
from apps.HttpAutoTestService.models import Testcase

__all__ = ['TestcaseFilter']


class TestcaseFilter(django_filters.rest_framework.FilterSet):
    """
    测试用例过滤
    """
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    status = django_filters.CharFilter(field_name='status', lookup_expr='exact')
    project = django_filters.CharFilter(method='project_filter')
    module = django_filters.CharFilter(method='module_filter')
    testsuite = django_filters.CharFilter(method='testsuite_filter')
    api = django_filters.CharFilter(method='api_filter')
    level = django_filters.CharFilter(method='level_filter')
    creator = django_filters.CharFilter(method='creator_filter')
    testcase_folder = django_filters.CharFilter(method='testcase_folder_filter')

    def project_filter(self, queryset, name, value):
        return queryset.filter(api__project_id=value)

    def module_filter(self, queryset, name, value):
        module_list = value.split(',')
        return queryset.filter(api__module_id__in=module_list)

    def api_filter(self, queryset, name, value):
        api_list = value.split(',')
        return queryset.filter(api_id__in=api_list)

    def testsuite_filter(self, queryset, name, value):
        if value:
            queryset = queryset.filter(testsuite__id=value).order_by('testsuite2testcase')
        return queryset

    def level_filter(self, queryset, name, value):
        level_list = value.split(',')
        return queryset.filter(level__in=level_list)

    def creator_filter(self, queryset, name, value):
        creator_list = value.split(',')
        return queryset.filter(creator_id__in=creator_list)

    def testcase_folder_filter(self, queryset, name, value):
        testcase_folder_list = value.split(',')
        return queryset.filter(testcase_folder__in=testcase_folder_list)

    class Meta:
        model = Testcase
        fields = ['name', 'status']
